import pymysql
from scrapy.utils.project import get_project_settings


def __init__(self):
	self.settings = get_project_settings()
	
	self.host = self.settings['MYSQL_HOST']
	self.port = self.settings['MYSQL_PORT']
	self.db = self.settings['MYSQL_DBNAME']
	self.user = self.settings['MYSQL_USER']
	self.passwd = self.settings['MYSQL_PASSWD']

# 连接到mysql，不连接到具体的数据库
def connectMysql(self):
	conn = pymysql.connect(host=self.host,
							port=self.port,
							user=self.user,
							passwd=self.passwd,
							charset='utf8mb4')
	return conn

# 连接到具体的数据库（settings中设置的MYSQL_DBNAME)
def connectDATAbase(self):
	conn = pymysql.connect(host=self.host,
							port=self.port,
							user=self.user,
							passwd=self.passwd,
							db=self.db,
							charset='utf8mb4')
	return conn

# 创建数据库
def createDatabase(self):
	#连接数据库
	conn = self.connectMysql()
	sql = "create database if not exists "+self.db
	cur = conn.cursor()
	cur.execute(sql)
	cur.close()
	conn.close()